package com.leo.config;

import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;
import org.apache.ibatis.session.SqlSessionFactory;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Primary;

import javax.sql.DataSource;

/**
 * @ClassName DataSourceConfig
 * @Description
 * @Author wangss
 * @date 2021.08.19 20:56
 * @Version 1.0
 */
@Configuration
@MapperScan(basePackages = "com.leo.basic.scheduler.dao", sqlSessionFactoryRef = "mysqlSqlSessionFactory")
public class DataSourceConfig {

    public static String systemOperLogTableName;
    public static String schedulerJObTableName;

    @Primary
    @Bean(name = "mysqldatasource")
    @ConfigurationProperties(prefix = "spring.datasource.druid")
    public DataSource createMysqlDataSource() {
        return DruidDataSourceBuilder.create().build();
    }

    @Bean(name = "mysqlSqlSessionFactory")
    @Primary
    public SqlSessionFactory mysqlSqlSessionFactory(@Qualifier("mysqldatasource") DataSource dataSource)
            throws Exception {
        final SqlSessionFactoryBean sessionFactory = new SqlSessionFactoryBean();
        sessionFactory.setDataSource(dataSource);
        return sessionFactory.getObject();
    }

    @Value("${spring.quartz.properties.org.quartz.jobStore.tablePrefix}")
    public void setTableName(String tablePrefix) {
        systemOperLogTableName = tablePrefix + "SYSTEM_OPERLOG";
        schedulerJObTableName = tablePrefix + "SCHEDULER_JOB";
    }
}
